package design.mode.effective_java.chapter2.item2;

/**
 * @author mingde
 * @date 2021/8/2 22:13
 * @describe 它结合了可伸缩构造函数模式的安全性和 JavaBean 模式的可读性。
 * 它是建造者模式的一种形式 [Gamma95]。客户端不直接生成所需的对象，
 * 而是使用所有必需的参数调用构造函数（或静态工厂），并获得一个 builder 对象。
 * 然后，客户端在构建器对象上调用像 setter 这样的方法来设置每个感兴趣的可选参数
 */
public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;

    public static class Builder {
        private final int servingSize;
        private final int servings;
        private int calories = 0;
        private int fat = 0;
        private int sodium = 0;
        private int carbohydrate = 0;

        public Builder(int servingSize, int servings) {
            this.servings = servings;
            this.servingSize = servingSize;
        }

        public Builder calories(int val) {
            this.calories = val;
            return this;
        }

        public Builder fat(int val) {
            fat = val;
            return this;
        }

        public Builder sodium(int val) {
            sodium = val;
            return this;
        }

        public Builder carbohydrate(int val) {
            carbohydrate = val;
            return this;
        }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    private NutritionFacts(Builder builder) {
        servings = builder.servings;
        servingSize = builder.servingSize;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }

    public static void main(String[] args) {
        NutritionFacts cocaCola  = new Builder(240,8)
                .calories(100).sodium(35).carbohydrate(27).build();
    }
}
